package com.aircraft.controller;

import com.aircraft.common.annotation.AccessLimit;
import com.aircraft.domain.vo.R;
import com.aircraft.domain.dto.Email;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.web.bind.annotation.*;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import javax.annotation.Resource;
import javax.mail.internet.MimeMessage;
import java.util.Arrays;

/**
 * 邮件
 */
@RestController
@RequestMapping("/mail")
public class MailController {

    @Value("${spring.mail.username}")
    private String from;

    @Resource
    private JavaMailSender mailSender;

    @Resource
    private TemplateEngine templateEngine;

    @AccessLimit(maxCount = 1)
    @RequestMapping(value = "/send",method = RequestMethod.POST)
    public R<?> sendEmail(@RequestBody Email email) {
        try {
            //创建邮件正文
            Context context = new Context();
            context.setVariable("verifyCode", Arrays.asList(email.getContent().split("")));
            //将模块引擎内容解析成html字符串
            String emailContent = templateEngine.process("captcha", context);
            //创建一个MINE消息
            MimeMessage message = mailSender.createMimeMessage();
            MimeMessageHelper minehelper = new MimeMessageHelper(message, true);
            //谁发
            minehelper.setFrom(from);
            //谁要接收
            minehelper.setTo(email.getTos());
            //邮件主题
            minehelper.setSubject(email.getSubject());
            //邮件内容   true 表示带有附件或html
            minehelper.setText(emailContent, true);
            mailSender.send(message);
            return R.ok(null,"HTML邮件成功");
        } catch (Exception e){
            e.printStackTrace();
            return R.fail( "邮件发送失败");
        }
    }
}